package admin

import (
	"fmt"
	"net/http"

	"gin-lite/internal/code"
	"gin-lite/internal/pkg/core"
	"gin-lite/internal/pkg/validation"
	"gin-lite/internal/repository/mysql/models"
)

type createRequest struct {
	Username string `json:"username" binding:"required"` // 用户名
	Mobile   string `json:"mobile" binding:"required"`   // 手机号
}

type createResponse struct {
	Id int32 `json:"id"` // 主键ID
}

// Create 创建管理员
// @Summary 创建管理员
// @Description 创建管理员
// @Tags API.admin
// @Accept application/x-www-form-urlencoded
// @Produce json
// @Param username formData string true "用户名"
// @Param mobile formData string true "手机号"
// @Success 200 {object} createResponse
// @Failure 400 {object} code.Failure
// @Router /api/admin [post]
func (h *handler) Create() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(createRequest)
		res := new(createResponse)
		if err := ctx.ShouldBindJSON(req); err != nil {
			ctx.AbortWithError(core.Error(http.StatusOK, code.ParamBindError, validation.Error(err)))
			return
		}

		var resultData *models.Admin
		h.db.GetConn().WithContext(ctx.RequestContext()).Where("username = ?", req.Username).First(&resultData)

		err := h.redis.Set(ctx.RequestContext(), "name_set", "王天来", -1).Err()
		if err != nil {
			panic(err)
		}

		var result any
		result, err = h.redis.Do(ctx.RequestContext(), "ping").Result()
		if err != nil {
			ctx.AbortWithError(core.Error(200, 1001, "执行redis命令失败").WithStack(err))
			return
		}
		fmt.Println(result)

		//var name string
		//name, err = h.redis.Get(ctx.RequestContext(), "name").Result()
		//if err == redis.Nil {
		//	fmt.Println("key2 does not exist")
		//} else if err != nil {
		//	panic(err)
		//} else {
		//	fmt.Println("key2", name)
		//}
		//fmt.Println(name)

		createData := new(models.Admin)
		createData.Username = req.Username
		createData.Mobile = req.Mobile

		dbResult := h.db.GetConn().WithContext(ctx.RequestContext()).Create(createData)

		if dbResult.Error != nil {
			ctx.AbortWithError(core.Error(http.StatusOK, code.AdminCreateError, code.Text(code.AdminCreateError)).WithStack(dbResult.Error))
			return
		}

		res.Id = createData.Id
		ctx.Payload(code.OK(res))
	}
}
